<template>
  <div style="margin-top: 20px; margin: 50px; margin-right: 100px">
    <!-- 按钮 -->

    <el-row>
      <el-button
        style="float: right"
        type="primary"
        @click="dialogFormVisible = true; dept={}"
      >+ 新增部门
      </el-button>
      <el-button type="primary" size="medium" @click="exportExcelFile" >导出表格</el-button>
      <el-button type="primary" size="medium" @click="importExcelFile" >导入表格</el-button>
      <input type="file" ref="excelFileInput" accept=".xls,.xlsx" style="display: none;" @change="handleExcelFileChange" />
    </el-row>
    <br>
    <!-- 数据表格 -->
    <template>
      <el-table
        ref="multipleTable"
        highlight-current-row
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
      >
        <el-table-column type="index" width="100" label="序号" header-align="center" align="center" />
        <el-table-column prop="name" label="部门名称" header-align="center" align="center" />
        <el-table-column label="最后操作时间" header-align="center" align="center">
          <template slot-scope="scope">
            {{ dayjs(scope.row.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="420" header-align="center" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              plain
              @click="selectById(scope.row.id)"
            >编辑
            </el-button>

            <el-button
              size="mini"
              type="danger"
              plain
              @click="deleteById(scope.row.id)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 新建对话框 -->

    <el-dialog title="保存部门" :visible.sync="dialogFormVisible">
      <el-form :model="dept">
        <el-form-item label="部门名称" :label-width="formLabelWidth">
          <el-input v-model="dept.name" placeholder="请输入部门名称" autocomplete="off" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { findAll, add, update, deleteById, selectById, exportExcel, importExcel } from '@/api/dept.js'
import dayjs from 'dayjs'
import {} from "@/api/clazz";

export default {
    data() {
        return {
            formLabelWidth: '120px',
            dialogFormVisible: false, // 控制对话框是否可见
            dept: {

                name: ''
            },
            tableData: []
        }
    },
    computed: {
        dayjs() {
            return dayjs
        }
    },
    mounted() {
    // 当页面加载完成后自动执行。
        this.init()
    },

    methods: {

        // 删除部门
        deleteById(id) {
            this.$confirm('确认删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteById(id).then((result) => {
                    this.$message({
                        message: '恭喜你，删除成功',
                        type: 'success'
                    })
                    // 重新查询数据
                    this.init()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            })
        },

        // 根据ID查询部门 -- 回显
        selectById(id) {
            this.dialogFormVisible = true
            selectById(id).then((result) => {
                this.dept = result.data
            })
        },

        // 保存方法
        add() {
            let method // 添加
            if (this.dept.id) {
                method = update(this.dept) // 修改
            } else {
                method = add(this.dept) // 添加
            }
            method.then((result) => {
                // 修改成功
                this.$message.success('恭喜你，保存成功')
                // 重新查询数据
                this.init()
            })
            // 关闭新建窗口
            this.dialogFormVisible = false

            // 清空模型数据
            this.dept = {}
        },
      exportExcelFile() {
        exportExcel().then(response => {
          const blob = new Blob(
            [response.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = '部门数据.xlsx';
          link.click();
          window.URL.revokeObjectURL(url);
        }).catch(error => {
          this.$message.error('导出失败：' + (error.response?.data?.msg || '网络错误'));
        });

      },
      // 导入Excel文件
      importExcelFile() {
        this.$refs.excelFileInput.click();
      },

      // 处理选择的Excel文件
      handleExcelFileChange(e) {
        const file = e.target.files[0];
        if (!file) return;
        // 验证文件类型
        const validTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
        if (!validTypes.includes(file.type)) {
          this.$message.error('请上传Excel文件（.xls或.xlsx）');
          return;
        }
        // 创建FormData并上传
        const formData = new FormData();
        formData.append('file', file);
        importExcel(formData).then(res => {
          if (res.data.code == '200') {
            this.$message.success('部门数据导入成功');
            this.init(); // 刷新表格数据
          } else {
            this.$message.error(res.data.msg || '导入失败，请检查文件内容');
          }
          // 清空文件输入
          this.$refs.excelFileInput.value = '';
        }).catch(err => {
          this.$message.error('网络错误，导入失败');
        });
      },

        // 初始化 - 查询全部
        init() {
            findAll().then((res) => {
                console.log(res)
                this.tableData = res.data
            })
        }
    }
}
</script>
<style>

</style>
